package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("CommentHotService")
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查找热点评论
     */
    @Override
    @Async("taskExecutor")
    public void hotCommentExecutor(ApComment apComment) {
        if (apComment.getLikes() < 10)
            return;
        // 查询当前文章下的所有热点评论集合
        List<ApComment> commentList = mongoTemplate.find(Query.query(
                                Criteria.where("articleId").is(apComment.getArticleId())
                                        .and("flag").is(1))
                        .with(Sort.by(Sort.Direction.DESC, "likes")).limit(5)
                , ApComment.class);
        if (commentList.size() < 5) {
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            commentList.add(apComment);
        } else {
            ApComment comment = commentList.get(commentList.size() - 1);

            //比较点赞数最小的评论和当前评论的点赞数
            if (comment.getLikes() < (apComment.getLikes())) {
                comment.setFlag((short) 0);
                mongoTemplate.save(comment);
                apComment.setFlag((short) 1);
                mongoTemplate.save(apComment);
            }
        }
    }
}
